# -*- coding: utf-8 -*-
"""
导出管理器
"""
from typing import Dict, Optional, Callable
import os
from datetime import datetime
from exporters import ExcelExporter, WordExporter, MarkdownExporter
from database.models import DatabaseManager
from config import SUPPORTED_FORMATS, DEFAULT_FORMAT

class ExportManager:
    """导出管理器"""
    
    def __init__(self):
        self.db_manager = DatabaseManager()
        self.exporters = {
            'Excel': ExcelExporter(),
            'Word': WordExporter(),
            'Markdown': MarkdownExporter()
        }
        self.current_exporter = None
        self.cancel_flag = False
    
    def set_progress_callback(self, callback: Callable[[int, str], None]):
        """设置进度回调函数"""
        for exporter in self.exporters.values():
            exporter.set_progress_callback(callback)
    
    def cancel_export(self):
        """取消导出"""
        self.cancel_flag = True
        for exporter in self.exporters.values():
            exporter.set_cancel_flag(True)
    
    def reset_cancel_flag(self):
        """重置取消标志"""
        self.cancel_flag = False
        for exporter in self.exporters.values():
            exporter.set_cancel_flag(False)
    
    def export_database_dict(self, dict_data: Dict, export_format: str, 
                           file_path: str, file_name: str, overwrite: bool = False) -> tuple[bool, str]:
        """
        导出数据库字典
        
        Args:
            dict_data: 数据库字典数据
            export_format: 导出格式
            file_path: 文件保存路径
            file_name: 文件名
            overwrite: 是否覆盖已存在的文件
            
        Returns:
            (导出是否成功, 错误信息)
        """
        try:
            # 验证导出格式
            if export_format not in self.exporters:
                return False, f"不支持的导出格式: {export_format}"
            
            # 验证文件路径
            if not self._validate_export_path(file_path):
                return False, "文件保存路径无效或无写入权限"
            
            # 生成完整文件路径
            file_extension = SUPPORTED_FORMATS[export_format]
            full_file_path = os.path.join(file_path, f"{file_name}{file_extension}")
            
            # 检查文件是否已存在
            if os.path.exists(full_file_path) and not overwrite:
                return False, f"文件已存在: {full_file_path}"
            
            # 重置取消标志
            self.reset_cancel_flag()
            
            # 获取导出器
            self.current_exporter = self.exporters[export_format]
            
            # 执行导出
            success = self.current_exporter.export(dict_data, full_file_path)
            
            if success:
                # 记录导出日志
                self._log_export_success(dict_data, export_format, file_path, file_name, full_file_path)
                return True, full_file_path
            else:
                error_msg = "导出过程中发生错误"
                if self.cancel_flag:
                    error_msg = "导出已取消"
                
                # 记录导出失败日志
                full_file_path = os.path.join(file_path, f"{file_name}{SUPPORTED_FORMATS[export_format]}")
                self._log_export_failure(dict_data, export_format, file_path, file_name, full_file_path, error_msg)
                return False, error_msg
                
        except Exception as e:
            error_msg = f"导出异常: {str(e)}"
            full_file_path = os.path.join(file_path, f"{file_name}{SUPPORTED_FORMATS[export_format]}")
            self._log_export_failure(dict_data, export_format, file_path, file_name, full_file_path, error_msg)
            return False, error_msg
    
    def _validate_export_path(self, file_path: str) -> bool:
        """验证导出路径"""
        try:
            # 检查路径是否存在
            if not os.path.exists(file_path):
                # 尝试创建目录
                os.makedirs(file_path)
            
            # 检查写入权限
            if not os.access(file_path, os.W_OK):
                return False
            
            return True
        except Exception:
            return False
    
    def _log_export_success(self, dict_data: Dict, export_format: str, 
                           file_path: str, file_name: str, full_file_path: str):
        """记录导出成功日志"""
        try:
            db_name = dict_data.get('database_info', {}).get('database_name', '')
            table_count = dict_data.get('total_tables', 0)
            
            # 保存完整文件名（包含扩展名）
            full_file_name = os.path.basename(full_file_path)
            
            self.db_manager.save_export_log(
                database_name=db_name,
                table_count=table_count,
                export_format=export_format,
                file_path=file_path,
                file_name=full_file_name,
                export_result="成功"
            )
        except Exception as e:
            print(f"记录导出成功日志失败: {e}")
    
    def _log_export_failure(self, dict_data: Dict, export_format: str, 
                           file_path: str, file_name: str, full_file_path: str, error_message: str):
        """记录导出失败日志"""
        try:
            db_name = dict_data.get('database_info', {}).get('database_name', '')
            table_count = dict_data.get('total_tables', 0)
            
            # 保存完整文件名（包含扩展名）
            full_file_name = os.path.basename(full_file_path)
            
            self.db_manager.save_export_log(
                database_name=db_name,
                table_count=table_count,
                export_format=export_format,
                file_path=file_path,
                file_name=full_file_name,
                export_result="失败",
                error_message=error_message
            )
        except Exception as e:
            print(f"记录导出失败日志失败: {e}")
    
    def get_export_logs(self, limit: int = 100) -> list:
        """获取导出日志"""
        try:
            return self.db_manager.get_export_logs(limit)
        except Exception as e:
            print(f"获取导出日志失败: {e}")
            return []
    
    def generate_default_filename(self, database_name: str = "") -> str:
        """生成默认文件名"""
        current_date = datetime.now().strftime('%Y%m%d')
        if database_name:
            return f"MySQL数据库字典_{database_name}_{current_date}"
        else:
            return f"MySQL数据库字典_{current_date}"
    
    def get_supported_formats(self) -> Dict[str, str]:
        """获取支持的导出格式"""
        return SUPPORTED_FORMATS.copy()
    
    def get_default_format(self) -> str:
        """获取默认导出格式"""
        return DEFAULT_FORMAT
